from datetime import datetime

from django.contrib import admin
from django.utils.html import format_html
from import_export.admin import ImportExportActionModelAdmin

from utils.shortcuts import get_object_or_none
from .models import Hosts, Disks, Network, Accessories
from .forms import HostsAdminForm
from .resources import HostsResource, AccessoriesResource


class DisksStackedInlineAdmin(admin.StackedInline):
    model = Disks
    extra = 1
    fieldsets = [
        (None, {'fields': [('capacity', 'tp', 'vendor')]})
    ]


class NetworkStackedInlineAdmin(admin.StackedInline):
    model = Network
    extra = 1
    fieldsets = [
        (None, {'fields': [('mac', 'ip'), ('name', 'speed', 'mtu')]})
    ]


class BaseMixin:
    def proposer(self, obj):
        if obj.username:
            return format_html(f'{obj.department}-{obj.username}')

    proposer.short_description = '责任人'

    def get_status(self, obj):
        if obj.status == 'used':
            color = '#ffa502'
        else:
            color = '#2ed573'
        return format_html(f'<span style="color:{color}">{obj.get_status_display()}</span>')

    get_status.short_description = '状态'

    def get_import_data_kwargs(self, request, *args, **kwargs):
        context = super().get_import_data_kwargs(request, *args, **kwargs)
        context.update(collect_failed_rows=True)
        return context

    def get_vendor_model(self, obj):
        if obj.vendor or obj.model:
            return f'{obj.vendor if obj.vendor is not None else ""} {obj.model if obj.model is not None else ""}'

    get_vendor_model.short_description = '品牌型号'

    def pc_type(self, obj):
        return obj.get_tp_display()

    pc_type.short_description = '类型'

    def get_export_filename(self, request, queryset, file_format):
        date_str = datetime.now().strftime('%Y-%m-%d')
        filename = "%s-%s.%s" % (self.model._meta.verbose_name,
                                 date_str,
                                 file_format.get_extension())
        return filename


@admin.register(Hosts)
class HostsAdmin(BaseMixin, ImportExportActionModelAdmin):
    """
    Host admin
    """
    resource_class = HostsResource
    inlines = [DisksStackedInlineAdmin, NetworkStackedInlineAdmin]
    date_hierarchy = 'created'
    list_display = ('asset_num', 'pc_type', 'get_vendor_model', 'sn', 'get_memory',
                    'get_disks', 'proposer', 'get_status', 'company', 'get_mac', 'updated')
    ordering = ('company', '-asset_num', 'cpu', 'updated')
    list_filter = ('company', 'tp', 'memory', 'status', 'vendor', 'model')
    search_fields = ('asset_num', 'tp', 'sn', 'cpu', 'username', 'department', 'company__name', 'comment')
    fieldsets = [
        (None, {'fields': [('tp', 'status'), ('sn', 'asset_num'), ('vendor', 'model'), ('username', 'department'),
                           'company', 'comment']}),
        ('CPU | 内存(GB)', {'fields': [('cpu', 'memory')]})
    ]

    def get_mac(self, obj):
        macs = obj.nics.values_list('mac', flat=True)
        return macs[0] if macs else ''

    get_mac.short_description = 'MAC'


@admin.register(Accessories)
class AccessoriesAdmin(BaseMixin, ImportExportActionModelAdmin):
    resource_class = AccessoriesResource
    date_hierarchy = 'created'
    list_display = ('asset_num', 'sn', 'pc_type', 'get_vendor_model', 'proposer', 'get_status','company', 'updated')
    ordering = ('-asset_num', 'updated', 'company')
    list_filter = ('company', 'tp', 'status', 'vendor', 'model')
    search_fields = ('asset_num', 'tp', 'sn', 'username', 'department', 'company__name', 'comment')
    fieldsets = [
        (None, {'fields': ['tp', ('sn', 'asset_num'), ('vendor', 'model'), ('username', 'department'),
                           ('status', 'company'), 'comment']}),
    ]
